//
//  YQRefreshControl.swift
//  zyqWeibo
//
//  Created by 张亚琼 on 15/7/4.
//  Copyright © 2015年 张亚琼. All rights reserved.
//

import UIKit
import FFAutoLayout

class YQRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        addSubview(refreshView)
        
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 150, height: 60))
        // KVO
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }
    
    // 显示提示图标标记
    private var showTipFlag = false
    // 加载动画标识
    private var loadingFlag = false
    // 监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // 如果是上推，直接返回
        if frame.origin.y > 0 {
            return
        }
        
        if refreshing && !loadingFlag {
//            print("正在加载啊。。。。。。")
            refreshView.startLoadingAnimate()
            loadingFlag = true
            return
        }
        
        // 如果过了临界点，并且标识为false
        if frame.origin.y < -50 && !showTipFlag {
//            print("用户向下拉了，箭头需要向上转")
            // 已经拉下来了，标识不需要再满足当前条件了，所以就设置标识为true，以保证下次走else
            showTipFlag = true
            refreshView.rotationTipIcon(showTipFlag)
            
         // 如果没到临界点，并且提示图标是true
        }else if frame.origin.y >= -50 && showTipFlag{
//            print("用户向上推了，箭头需要向下转")
            
            // 提示图标改为false，好让下次走另一个if分支
            showTipFlag = false
            refreshView.rotationTipIcon(showTipFlag)
        }
        
    }
    // 重写停止刷新方法
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoadingAnimate()
        
        // 重新设置关闭flag，否则下次无法开启刷新动画
        loadingFlag = false
    }
    // 注销监听
    deinit {
        refreshView.removeObserver(self, forKeyPath: "frame")
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 懒加载控件
    lazy var refreshView = RefreshView.refreshView()

}

class RefreshView: UIView {
    // 箭头图片
    @IBOutlet weak var tipImage: UIImageView!
    // 转圈图片
    @IBOutlet weak var loadingImage: UIImageView!
    // 刷新view
    @IBOutlet weak var innerView: UIView!
    
    // 从xib加载
    class func refreshView() -> RefreshView {
       return NSBundle.mainBundle().loadNibNamed("YQRefreshView", owner: nil, options: nil).last as! RefreshView
    }
    
    // 旋转箭头
    private func rotationTipIcon(clockWise: Bool) {
        // clockWise 为true表示是向上转，为false表示向下转
        UIView.animateWithDuration(0.5) { () -> Void in
            var angle = M_PI
            angle += clockWise ? -0.01 : 0.01
            self.tipImage.transform = CGAffineTransformRotate(self.tipImage.transform, CGFloat(angle))
        }
    }
    
    // 开始动画
    private func startLoadingAnimate() {
        innerView.hidden = true
        let animate = CABasicAnimation(keyPath: "transform.rotation")
        animate.toValue = 2 * M_PI
        animate.duration = 5
        animate.repeatCount = MAXFLOAT
        
        loadingImage.layer.addAnimation(animate, forKey: nil)
        
    }
    
    // 结束动画
    private func stopLoadingAnimate() {
        innerView.hidden = false
        loadingImage.layer.removeAllAnimations()
        
    }
}
